import 'package:flutter/material.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:get/get.dart';

class ForgetPwdSetController extends BaseController {
  String pwd = "";
  String pwdConfirm = "";
  bool isCorrectPwd = false;
  HttpClient client = Get.find<HttpClient>();
  String code = Get.arguments['code'];
  String mobile = Get.arguments['mobile'];

  Future<bool> resetPwd() async {
    if (!isCorrectPwd) return false;
    try {
      DialogUtil.showLoading();
      await client.post(AddressManager.resetPwd, data: {
        "code": code,
        "mobile": mobile,
        "password": pwd,
      });
      ToastUtil.showSuccess("修改成功!");
      Get.back();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  void isCorrect() {
    final pattern = RegExp(
        r"^(?=.*[a-zA-Z])(?=.*[0-9!@#\$%\^&\*])(?=.{6,20})(?![\u4e00-\u9fa5]).*$");
    if (!pattern.hasMatch(pwd) ||
        !pattern.hasMatch(pwdConfirm) ||
        pwd != pwdConfirm) {
      isCorrectPwd = false;
    } else {
      isCorrectPwd = true;
    }
    update(['confirm']);
  }

  void onConfirm() {
    final pattern = RegExp(
        r"^(?=.*[a-zA-Z])(?=.*[0-9!@#\$%\^&\*])(?=.{6,20})(?![\u4e00-\u9fa5]).*$");
    if (!pattern.hasMatch(pwd)) {
      ToastUtil.showTips("密码请输入6-20位字符，不可以是纯数字或者符号");
      return;
    }
    if (pwd != pwdConfirm) {
      ToastUtil.showTips("两次密码不一致");
      return;
    }
    resetPwd();
  }
}
